﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Script.Serialization;
using System.Net.Mail;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;

namespace iver.Controllers
{


    /// <summary>
    /// 响应结果基础方法类
    /// </summary>
    public class ReqBase
    {
        /// <summary>
        /// 响应结果
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <returns>返回结果字符串</returns>
        public static string ResResult(bool success)
        {
            return $@"{{
                ""success"":{success.ToString().ToLower()}
                }}";
        }
        /// <summary>
        /// 响应结果
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <param name="rescode">响应结果码/错误码（可以空）</param>
        /// <returns>返回结果字符串</returns>
        public static string ResResult(bool success, int rescode)
        {
            return $@"{{
                ""success"":{success.ToString().ToLower()},
                ""rescode"":{rescode}
                }}";
        }
        /// <summary>
        /// 响应结果
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <param name="rescode">响应结果码/错误码（可以空）</param>
        /// <param name="result">响应结果消息/错误消息 如(登录成功/验证码错误)(可以空) 按需求自行编写</param>
        /// <returns>返回结果字符串</returns>
        public static string ResResult(bool success, int rescode, string result)
        {
            string firstLetter = result.Substring(0, 1);
            if (firstLetter == "[" || firstLetter == "{")
            {
                return $@"{{
                ""success"":{success.ToString().ToLower()},
                ""rescode"":{rescode},
                ""result"":{result}
                }}";
            }
            else
            {
                return $@"{{
                ""success"":{success.ToString().ToLower()},
                ""rescode"":{rescode},
                ""result"":""{result}""
                }}";
            }

        }
        public static string ResResult(bool success, int rescode, int count, System.Data.DataTable dt)
        {
            return $@"{{
                ""success"":{success.ToString().ToLower()},
                ""rescode"":{rescode},
                ""result"":{{
                    ""count"":{count},
                    ""arr"":{Help.DataTableToJson(dt)}
                }}
            }}";
        }

        #region isAuth
        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="authInfo"></param>
        /// <returns></returns>
        public static bool isAuth(out Entity.AuthInfo authInfo, bool isCheckControlPage = true)
        {
            authInfo = new Entity.AuthInfo();

            string token = System.Web.HttpContext.Current.Request.Headers["auth"];

            string str = "";

            ////取得当前方法命名空间    
            //str += "命名空间名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "\n";

            ////取得当前方法类全名 包括命名空间    
            //str += "类名:" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "\n";

            ////取得当前方法名    
            //str += "方法名:" + System.Reflection.MethodBase.GetCurrentMethod().Name + "\n"; str += "\n";

            ////父方法
            //System.Diagnostics.StackTrace ss = new System.Diagnostics.StackTrace(true);
            //System.Reflection.MethodBase mb = ss.GetFrame(1).GetMethod();

            ////取得父方法命名空间    
            //str += mb.DeclaringType.Namespace + "\n";

            ////取得父方法类名    
            //str += mb.DeclaringType.Name + "\n";

            ////取得父方法类全名    
            //str += mb.DeclaringType.FullName + "\n";

            ////取得父方法名    
            //str += mb.Name + "\n";

            //对token进行解密
            string secureKey = System.Configuration.ConfigurationManager.AppSettings["SecureKey"];
            try
            {
                authInfo = JWT.JsonWebToken.DecodeToObject<Entity.AuthInfo>(token, secureKey);
                if (authInfo.createTime != null)
                {
                    //设置token过期时间
                    if (Convert.ToDateTime(authInfo.createTime).AddHours(12) < DateTime.Now)
                    {
                        return false;
                    }

                }
                if (!authInfo.isSuperAdmin && isCheckControlPage)
                {
                    int count = authInfo.moduleList.Count;
                    if (count > 0)
                    {
                        //父方法
                        System.Diagnostics.StackTrace ss = new System.Diagnostics.StackTrace(true);
                        System.Reflection.MethodBase mb = ss.GetFrame(1).GetMethod();
                        //取得父方法类名    
                        string className = mb.DeclaringType.Name;
                        bool flag = false;
                        for (int i = 0; i < authInfo.moduleList.Count; i++)
                        {
                            if (className.ToLower() == authInfo.moduleList[i].moduleName.ToLower())
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag)
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

            //authInfo = new Entity.AuthInfo();
            //authInfo.userId = 1;
            //authInfo.userName = "haozhi";
            //authInfo.isSuperAdmin = true;
            //return true;
        }
        #endregion

    }
    /// <summary>
    /// common
    /// </summary>
    public class Help
    {
        #region 数据库层面
        /// <summary>
        /// 获取用户的管理权限
        /// </summary>
        /// <param name="req"></param>
        /// <param name="authInfo"></param>
        /// <returns></returns>
        public static List<DBEntity.sysModule> BaseModuleList(Entity.AuthInfo authInfo)
        {
            DBEntity.iverDB db = new DBEntity.iverDB();
            //模块列表
            List<DBEntity.sysModule> BaseModuleList;
            if (authInfo.isSuperAdmin)
            {
                //超级管理员获取所有可用列表
                BaseModuleList = (from u in db.sysModule
                                  where u.isEnable == true
                                  orderby u.orderNum descending
                                  select u).ToList();
            }
            else
            {
                //普通管理员获取自己可用列表
                BaseModuleList = (from u in db.sysRoleModule
                                  join u3 in db.sysModule on u.moduleId equals u3.id into temp3
                                  from module in temp3.DefaultIfEmpty()
                                  join u1 in db.sysRole on u.roleId equals u1.id into temp1
                                  from role in temp1.DefaultIfEmpty()
                                  join u2 in db.sysUserRole on role.id equals u2.roleId into temp2
                                  from userRole in temp2.DefaultIfEmpty()
                                  where userRole.userId == authInfo.userId && module.isEnable == true
                                  orderby module.orderNum descending
                                  select module).GroupBy(p => p).Select(p => p.Key).ToList();
            }
            return BaseModuleList;
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="authInfo"></param>
        /// <param name="result"></param>
        public static void Log(Entity.AuthInfo authInfo, string result)
        {
            //父方法
            System.Diagnostics.StackTrace ss = new System.Diagnostics.StackTrace(true);
            System.Reflection.MethodBase mb = ss.GetFrame(1).GetMethod();
            //取得父方法类名    
            string className = mb.DeclaringType.Name;
            //获取父类的方法名
            string methodName = mb.Name;
            DBEntity.iverDB db = new DBEntity.iverDB();
            DBEntity.sysUserLog model = new DBEntity.sysUserLog();
            model.userName = authInfo.userName;
            model.ipAddress = authInfo.IP;
            model.createTime = DateTime.Now;
            model.targetName = className + "|" + methodName;
            model.result = result;
            db.sysUserLog.Add(model);
            db.SaveChanges();
        }
        /// <summary>
        /// 将数据库apconfig静态化成JS文件
        /// </summary>
        public static void StaticApConfig()
        {
            DBEntity.iverDB db = new DBEntity.iverDB();
            var list = (from u in db.apConfig
                        select u);
            List<DBEntity.apConfig> mylist = list.ToList();
            string temp = "";
            for (int i = 0; i < mylist.Count; i++)
            {
                string name = mylist[i].name;
                string jsonString = mylist[i].jsonString;
                string obj = $"{name}:{jsonString},";
                temp += obj;
            }
            temp = temp.Substring(0, temp.Length - 1);

            string myDir = AppDomain.CurrentDomain.BaseDirectory + @"config\";
            if (!System.IO.Directory.Exists(myDir))
            {
                System.IO.Directory.CreateDirectory(myDir);
            }
            System.IO.StreamWriter sw = System.IO.File.CreateText(myDir + "home.js");
            sw.WriteLine("window.iverhome = {" + temp + "}");
            sw.Flush();
            sw.Close();
        }
        /// <summary>
        /// 将数据库apconfig静态化成JS文件
        /// </summary>
        public static void StaticApInfoType()
        {
            DBEntity.iverDB db = new DBEntity.iverDB();
            var list = (from u in db.apInfoType
                        where u.isEnable == true
                        orderby u.orderNum descending
                        select u);
            List<DBEntity.apInfoType> mylist = list.ToList();
            string temp = Newtonsoft.Json.JsonConvert.SerializeObject(mylist);

            //string temp = "";
            //for (int i = 0; i < mylist.Count; i++)
            //{
            //    string name = mylist[i].name;
            //    string jsonString = mylist[i].jsonString;
            //    string obj = $"{name}:{jsonString},";
            //    temp += obj;
            //}
            //temp = temp.Substring(0, temp.Length - 1);

            string myDir = AppDomain.CurrentDomain.BaseDirectory + @"config\";
            if (!System.IO.Directory.Exists(myDir))
            {
                System.IO.Directory.CreateDirectory(myDir);
            }
            System.IO.StreamWriter sw = System.IO.File.CreateText(myDir + "infotype.js");
            sw.WriteLine("window.iverinfotype = " + temp);
            sw.Flush();
            sw.Close();
        }
        #endregion

        #region 工具类
        /// <summary>
        /// 得到IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIPAddress()
        {

            string user_IP = string.Empty;
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                {
                    user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                }
                else
                {
                    user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
                }
            }
            else
            {
                user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return user_IP;
        }
        /// <summary>
        /// 追加写文件txt
        /// </summary>
        /// <param name="writeStr">字符串</param>
        /// <param name="fileName">文件名，无后缀</param>
        public static void SaveNote(string writeStr, string fileName)
        {
            try
            {
                string myDir = AppDomain.CurrentDomain.BaseDirectory + @"log\";
                if (!System.IO.Directory.Exists(myDir))
                {
                    System.IO.Directory.CreateDirectory(myDir);
                }
                System.IO.StreamWriter sw = System.IO.File.AppendText(myDir + fileName + ".txt");

                sw.WriteLine(writeStr);
                sw.Flush();
                sw.Close();
            }
            catch
            {

            }
        }
        /// <summary>
        /// DataTableToJson
        /// </summary>
        /// <param name="table">datatable</param>
        /// <returns>jsonstr</returns>
        public static string DataTableToJson(DataTable table)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
            Dictionary<string, object> childRow;
            foreach (DataRow row in table.Rows)
            {
                childRow = new Dictionary<string, object>();
                foreach (DataColumn col in table.Columns)
                {
                    childRow.Add(col.ColumnName, row[col]);
                }
                parentRow.Add(childRow);
            }
            string jsonStr = jsSerializer.Serialize(parentRow);
            jsonStr = System.Text.RegularExpressions.Regex.Replace(jsonStr, @"\\/Date\((\d+)\)\\/", match =>
            {
                DateTime dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                dt = dt.ToLocalTime();
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            });
            return jsonStr;
        }
        /// <summary>
        /// 使用qq发邮件
        /// </summary>
        /// <param name="title">邮件标题</param>
        /// <param name="body">邮件内容</param>
        /// <param name="toWhom">发送给谁</param>
        /// <param name="uid">uid</param>
        /// <param name="pwd">pwd</param>
        public static void SendMail(string title, string body, string toWhom, string uid = "myenname@qq.com", string pwd = "123456")
        {
            using (MailMessage mailMessage = new MailMessage())
            using (SmtpClient smtpClient = new SmtpClient("smtp.163.com", 25))
            {
                mailMessage.To.Add(toWhom);
                mailMessage.Body = body;
                //设置邮件内容是否是 HTML 格式
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = Encoding.UTF8;
                mailMessage.From = new MailAddress("myenname@163.com", "杨春湖实验学校");
                mailMessage.Subject = title;
                mailMessage.SubjectEncoding = Encoding.UTF8;
                //smtpClient.EnableSsl = true;
                //qq启用了“客户端授权码”，要用授权码代替密码
                smtpClient.Credentials = new NetworkCredential(uid, pwd);
                smtpClient.Send(mailMessage);
            }
        }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param> 
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {


            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);



            int towidth = width;
            int toheight = height;


            int x = 0;
            int y = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;


            switch (mode)
            {
                case "HW"://指定高宽缩放（可能变形）                
                    break;
                case "W"://指定宽，高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    break;
                case "H"://指定高，宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    break;
                case "Cut"://指定高宽裁减（不变形）                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh = originalImage.Height;
                        ow = originalImage.Height * towidth / toheight;
                        y = 0;
                        x = (originalImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width * height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }
                    break;
                default:
                    break;
            }


            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);


            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);


            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;


            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;


            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);


            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);


            try
            {
                System.Drawing.Imaging.ImageFormat f;
                string exback = System.IO.Path.GetExtension(originalImagePath).ToLower();
                if (exback == "jpg" || exback == "jpeg")
                {
                    f = System.Drawing.Imaging.ImageFormat.Jpeg;
                }
                else if (exback == "png")
                {
                    f = System.Drawing.Imaging.ImageFormat.Png;
                }
                else if (exback == "gif")
                {
                    f = System.Drawing.Imaging.ImageFormat.Gif;
                }
                else
                {
                    f = System.Drawing.Imaging.ImageFormat.Jpeg;
                }
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, f);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        /// <summary>
        /// 无损压缩图片
        /// </summary>
        /// <param name="sFile">原图片地址</param>
        /// <param name="dFile">压缩后保存图片地址</param>
        /// <param name="flag">压缩质量（数字越小压缩率越高）1-100</param>
        /// <param name="size">压缩后图片的最大大小</param>
        /// <param name="sfsc">是否是第一次调用</param>
        /// <returns></returns>
        public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 300, bool sfsc = true)
        {
            //如果是第一次调用，原始图像的大小小于要压缩的大小，则直接复制文件，并且返回true
            FileInfo firstFileInfo = new FileInfo(sFile);
            if (sfsc == true && firstFileInfo.Length < size * 1024)
            {
                firstFileInfo.CopyTo(dFile);
                return true;
            }
            System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
            ImageFormat tFormat = iSource.RawFormat;
            int dHeight = iSource.Height / 2;
            int dWidth = iSource.Width / 2;
            int sW = 0, sH = 0;
            //按比例缩放
            Size tem_size = new Size(iSource.Width, iSource.Height);
            if (tem_size.Width > dHeight || tem_size.Width > dWidth)
            {
                if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
                {
                    sW = dWidth;
                    sH = (dWidth * tem_size.Height) / tem_size.Width;
                }
                else
                {
                    sH = dHeight;
                    sW = (tem_size.Width * dHeight) / tem_size.Height;
                }
            }
            else
            {
                sW = tem_size.Width;
                sH = tem_size.Height;
            }

            Bitmap ob = new Bitmap(dWidth, dHeight);
            Graphics g = Graphics.FromImage(ob);

            g.Clear(Color.WhiteSmoke);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

            g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

            g.Dispose();

            //以下代码为保存图片时，设置压缩质量
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;

            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
                    FileInfo fi = new FileInfo(dFile);
                    if (fi.Length > 1024 * size)
                    {
                        flag = flag - 10;
                        CompressImage(sFile, dFile, flag, size, false);
                    }
                }
                else
                {
                    ob.Save(dFile, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                ob.Dispose();
            }
        }
        /////　<summary>
        /////　获取媒体文件属性信息
        /////　</summary>
        //public static List<string> GetFileDetailInfo(string strPath)
        //{
        //    Shell32.ShellClass sh = new Shell32.ShellClass();
        //    Shell32.Folder dir = sh.NameSpace(System.IO.Path.GetDirectoryName(strPath));

        //    Shell32.FolderItem folderItem = dir.ParseName(System.IO.Path.GetFileName(strPath));
        //    string[] strs = dir.GetDetailsOf(folderItem, -1).Split('\n');
        //    List<string> list = new List<string>();
        //    list.Add($"文件名|{dir.GetDetailsOf(folderItem, 0)}");
        //    list.Add($"修改时间|{dir.GetDetailsOf(folderItem, 3)}");
        //    list.Add($"创建时间|{dir.GetDetailsOf(folderItem, 4)}");
        //    for (int i = 0; i < strs.Length; i++)
        //    {
        //        list.Add(System.Text.RegularExpressions.Regex.Replace(strs[i].Trim(), @":\s", "|"));
        //    }

        //    return list;
        //}
        ///　<summary>
        ///　获取媒体文件属性信息
        ///　</summary>
        public static string GetValueByKey(string key, List<string> list)
        {
            string value = "";
            for (int i = 0; i < list.Count; i++)
            {
                string[] ss = list[i].Split('|');
                if (ss[0] == key)
                {
                    value = ss[1];
                    break;
                }
            }
            return value;
        }
        /// <summary>
        /// 设置文件属性
        /// </summary>
        public static void SetFileAttr(string filePath, Microsoft.WindowsAPICodePack.Shell.PropertySystem.PropertyKey key, object value)
        {
            var file = Microsoft.WindowsAPICodePack.Shell.ShellFile.FromFilePath(filePath);
            Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyWriter propertyWriter = file.Properties.GetPropertyWriter();
            propertyWriter.WriteProperty(key, value);
            propertyWriter.Close();
        }
        ///// <summary>
        ///// 获取文件属性
        ///// </summary>
        public static Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellProperties.PropertySystem GetFileAttr(string filePath)
        {
            var file = Microsoft.WindowsAPICodePack.Shell.ShellFile.FromFilePath(filePath);
            return file.Properties.System;
        }
        /// <summary>
        /// 限制单位时间内的请求次数
        /// </summary>
        /// <param name="second">单位时间：秒</param>
        /// <param name="time">请求次数</param>
        /// <param name="flagName">请求表示名，项目中不要重复</param>
        /// <returns>剩余的请求次数，-1为单位时间内已经用尽了请求次数，大于等于0表示在请求限制次数内</returns>
        public static int checkReqTime(double second, int time, string flagName)
        {
            if (System.Web.HttpContext.Current.Session[flagName + "reqTime"] == null)
            {
                //首次请求
                System.Web.HttpContext.Current.Session[flagName + "reqTime"] = DateTime.Now;
                System.Web.HttpContext.Current.Session[flagName + "time"] = time - 1;
                return time - 1;
            }
            DateTime sdt = Convert.ToDateTime(System.Web.HttpContext.Current.Session[flagName + "reqTime"]);
            DateTime now = DateTime.Now;
            int s = DateTime.Compare(sdt.AddSeconds(second), now);
            if (s < 0)
            {
                //超过了规定的时间
                System.Web.HttpContext.Current.Session[flagName + "reqTime"] = now;
                System.Web.HttpContext.Current.Session[flagName + "time"] = time - 1;
                return time - 1;
            }
            else
            {
                //在固定的时间内
                int resultTime = Convert.ToInt32(System.Web.HttpContext.Current.Session[flagName + "time"]) - 1;
                System.Web.HttpContext.Current.Session[flagName + "time"] = resultTime;
                if (resultTime < 0)
                {
                    //使用次数已经用尽
                    return -1;
                }
                return resultTime;
            }
        }
        #endregion

        #region 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="typeName">文件夹名</param>
        /// <param name="maxSize">最大上传尺寸M</param>
        /// <returns></returns>
        public static ResResult uploadfile(string typeName = "img", int maxSize = 0)
        {
            string pathName = "/up/" + typeName + "/";
            HttpFileCollection files = HttpContext.Current.Request.Files;

            //判断是否有文件上传
            if (files.Count == 0)
            {
                return new ResResult
                {
                    success = false,
                    rescode = ResCode.FailParams,
                    result = "没有选择上传文件",
                };
            }

            string createDir = System.Web.HttpContext.Current.Server.MapPath("~" + pathName);
            if (!System.IO.Directory.Exists(createDir))
            {
                System.IO.Directory.CreateDirectory(createDir);
            }

            //判断文件大小
            if (maxSize != 0)
            {
                bool sizeflag = true;
                string fileName = "";
                int fileSize = 0;
                for (int i = 0; i < files.Count; i++)
                {
                    int inputSize = files[i].ContentLength;
                    if (files[i].ContentLength / 1024 / 1024 >= maxSize)
                    {
                        sizeflag = false;
                        fileName = files[i].FileName;
                        fileSize = inputSize;
                        break;
                    }
                }
                if (!sizeflag)
                {
                    return new ResResult
                    {
                        success = false,
                        rescode = ResCode.FailParams,
                        result = new
                        {
                            fileName,
                            fileSize,
                            maxSize,
                        },
                    };
                }
            }


            //返回的网络地址数组
            List<string> webPathList = new List<string>();
            for (int i = 0; i < files.Count; i++)
            {
                string FileEextension = System.IO.Path.GetExtension(files[i].FileName);
                string id = Guid.NewGuid().ToString("N");
                string webpath = pathName + id + FileEextension;
                webPathList.Add(webpath);
                string filepath = createDir + id + FileEextension;
                files[i].SaveAs(filepath);
            }

            return new ResResult
            {
                success = true,
                result = webPathList,
            };
        }
        #endregion

        #region 图片验证码
        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <returns></returns>
        public static ResResult imgcode(ReqImgCode req)
        {
            //System.Threading.Thread.Sleep(4000);
            try
            {
                string code = GetRandomCode(4);
                System.Web.HttpContext.Current.Session["imgcode"] = code;
                return new ResResult()
                {
                    success = true,
                    result = "data:image/png;base64," + Convert.ToBase64String(getBytes(code, req.fontsize, req.width, req.height))
                };
            }
            catch
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                    result = "图片生成错误"
                };
            }
        }
        /// <summary>
        /// 生成图片验证码
        /// </summary>
        /// <returns></returns>
        public static string imgCode(ReqImgCode req)
        {
            //System.Threading.Thread.Sleep(4000);
            try
            {
                string code = GetRandomCode(4);
                System.Web.HttpContext.Current.Session["imgcode"] = code;
                return "data:image/png;base64," + Convert.ToBase64String(getBytes(code, req.fontsize, req.width, req.height));
            }
            catch
            {
                return "";
            }
        }
        public static string GetRandomCode()
        {
            int VcodeNum = 4;
            StringBuilder sb = new StringBuilder(VcodeNum);
            Random rand = new Random();
            for (int i = 1; i < VcodeNum + 1; i++)
            {
                int t = rand.Next(9);
                sb.AppendFormat("{0}", t);
            }
            return sb.ToString();

        }
        private static string GetRandomCode(int CodeCount)
        {
            //string allChar = "0,1,2,3,4,5,6,7,8,9";
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string RandomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < CodeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
                }

                //int t = rand.Next(10);
                int t = rand.Next(33);

                while (temp == t)
                {
                    //t = rand.Next(10);
                    t = rand.Next(33);
                }

                temp = t;
                RandomCode += allCharArray[t];
            }

            return RandomCode;
        }
        private static byte[] getBytes(string validateCode, int fontsize = 18, int width = 30, int height = 30)
        {
            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width * 4, height);//设置长度和宽度分别为80和20
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);//Bitmap是Image的子类，所以可以替换Image放置在函数中
            char[] ch = validateCode.ToCharArray();
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(System.Drawing.Color.White);

                int p_y = Convert.ToInt32((height - fontsize) / 2);
                int p_x = Convert.ToInt32((width - fontsize) / 2);
                for (int i = 0; i < ch.Length; i++)
                {

                    System.Drawing.Point p = new System.Drawing.Point(i * width + p_x, p_y - 6);
                    //string[] fonts = { "微软雅黑" };
                    string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" };
                    System.Drawing.Color[] colors = { System.Drawing.Color.Blue, System.Drawing.Color.Black, System.Drawing.Color.Red, System.Drawing.Color.Green };
                    g.DrawString(ch[i].ToString(), new System.Drawing.Font(fonts[random.Next(0, 5)], fontsize, System.Drawing.FontStyle.Bold), new System.Drawing.SolidBrush(colors[random.Next(0, 4)]), p);
                }
                //画线
                for (int i = 0; i < 10; i++)
                {
                    System.Drawing.Point p1 = new System.Drawing.Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height));
                    System.Drawing.Point p2 = new System.Drawing.Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height));
                    g.DrawLine(new System.Drawing.Pen(System.Drawing.Brushes.Green), p1, p2);
                }
                //画点
                for (int i = 0; i < 50; i++)
                {
                    System.Drawing.Point p = new System.Drawing.Point(random.Next(0, bmp.Width), random.Next(0, bmp.Height));
                    bmp.SetPixel(p.X, p.Y, System.Drawing.Color.Black);
                }
                //保存图片数据
                System.IO.MemoryStream stream = new System.IO.MemoryStream();
                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);

                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
            }

        }
        #endregion

        #region 读写文件数据库
        public static ResResult writetable(ReqKeyValuePair req)
        {

            string tablePath = System.Web.HttpContext.Current.Server.MapPath("~/table");
            try
            {
                if (!System.IO.Directory.Exists(tablePath))
                {
                    System.IO.Directory.CreateDirectory(tablePath);
                }
                string filePath = tablePath + "/" + req.name + ".json";
                System.IO.File.WriteAllText(filePath, req.jsonString);
                return new ResResult()
                {
                    success = true,
                };
            }
            catch
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                };
            }


        }
        public static ResResult readtable(ReqKeyValuePair req)
        {

            string tablePath = System.Web.HttpContext.Current.Server.MapPath("~/table");
            try
            {
                if (!System.IO.Directory.Exists(tablePath))
                {
                    System.IO.Directory.CreateDirectory(tablePath);
                }
                string filePath = tablePath + "/" + req.name + ".json";
                if (!System.IO.File.Exists(filePath))
                {
                    return new ResResult()
                    {
                        success = false,
                        rescode = ResCode.FailParams,
                        result = "没有找到对应信息"
                    };
                }
                return new ResResult()
                {
                    success = true,
                    result = System.IO.File.ReadAllText(filePath)
                };
            }
            catch
            {
                return new ResResult()
                {
                    success = false,
                    rescode = ResCode.FailCatch,
                };
            }

        }
        #endregion

        #region 调用CMD
        /// <summary>
        /// 执行cmd命令
        /// 多命令请使用批处理命令连接符：
        /// <![CDATA[
        /// &:同时执行两个命令
        /// |:将上一个命令的输出,作为下一个命令的输入
        /// &&：当&&前的命令成功时,才执行&&后的命令
        /// ||：当||前的命令失败时,才执行||后的命令]]>
        /// 其他请百度
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="output"></param>
        public static void RunCmd(string cmd, out string output)
        {
            cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明：不管命令是否成功均执行exit命令，否则当调用ReadToEnd()方法时，会处于假死状态
            using (System.Diagnostics.Process p = new System.Diagnostics.Process())
            {
                p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //向cmd窗口写入命令
                p.StandardInput.WriteLine(cmd);
                p.StandardInput.AutoFlush = true;

                //获取cmd窗口的输出信息
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
        }
        //调用
        //string cmd = @"d:&cd D:\video-zw\excel&node dir";
        //string output = "";
        //RunCmd(cmd, out output);
        //this.mydiv.InnerHtml = output;
        #endregion
    }
}